/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package z.h.w.jar.kit.clazz;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Arrays;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

/**
 *
 * @author EnzoZhong
 */
public class PasswordEncryptionService {

      public boolean authenticate ( String attemptedPassword , byte[] encryptedPassword ) {
            byte[] encryptedAttemptedPassword = null;
            encryptedAttemptedPassword = getEncryptedPassword ( attemptedPassword );
            return Arrays.equals ( encryptedPassword , encryptedAttemptedPassword );
      }

      public byte[] getEncryptedPassword ( String password ) {
            try {
                  KeySpec spec = new PBEKeySpec ( password.toCharArray () );
                  SecretKeyFactory f = SecretKeyFactory.getInstance ( "PBKDF2WithHmacSHA1" );
                  return f.generateSecret ( spec ).getEncoded ();
            } catch ( NoSuchAlgorithmException | InvalidKeySpecException ex ) {
                  return null;
            }
      }

      public byte[] generateSalt () throws NoSuchAlgorithmException {
            SecureRandom random = SecureRandom.getInstance ( "SHA1PRNG" );
            byte[] salt = new byte[ 8 ];
            random.nextBytes ( salt );
            return salt;
      }

}
